package com.advertisementsystem.Controller;

import com.advertisementsystem.Dto.AdvertisementDTO;
import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.Servie.AdvertisementService;
import com.advertisementsystem.entity.Advertisement;
import com.advertisementsystem.Exception.ResponseResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/advertisement")
@Slf4j
public class AdvertisementController {

    @Autowired
    private AdvertisementService advertisementService;
    // 创建广告  11
    @PostMapping
    @PreAuthorize("hasAuthority('ad:create')")
    public ResponseResult<?> createAdvertisement(@RequestBody @Valid AdvertisementDTO dto) {
        log.info("{}",dto);
        advertisementService.createAdvertisement(dto);
        return ResponseResult.success("");
    }

    // 更新广告 11
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('ad:update')")
    public ResponseResult<?> updateAdvertisement(
            @PathVariable Long id,
            @RequestBody @Valid AdvertisementDTO dto) {
        advertisementService.updateAdvertisement(id, dto);
        return ResponseResult.success("");
    }

    // 删除广告 11
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('ad:delete')")
    public ResponseResult<?> deleteAdvertisement(@PathVariable Long id) {
        log.info("{}",id);
        advertisementService.deleteAdvertisement(id);
        return ResponseResult.success("");
    }

    // 获取广告列表 11
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('ad:list')")
    public ResponseResult<Page<Advertisement>> getAdvertisementList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String budget,
            @RequestParam(required = false, defaultValue = "time_desc") String sort,
            @RequestParam(required = false) Integer type
    ) {
        log.info("获取广告列表，页码：{}，每页大小：{}，关键词：{}，状态：{}，预算：{}，排序：{}", pageNum, pageSize, keyword, status, budget, sort);
        return ResponseResult.success(advertisementService.getAdvertisementList(pageNum, pageSize, keyword, status, budget, sort,type));
    }



    // 获取广告详情 11
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('ad:list')")
    public ResponseResult<Advertisement> getAdvertisementDetail(@PathVariable Long id) {
        return ResponseResult.success(advertisementService.getAdvertisementDetail(id));
    }

    // 审核通过广告 11
    @PutMapping("/{id}/approve")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseResult<?> approveAdvertisement(@PathVariable Long id) {
        advertisementService.approveAdvertisement(id);
        return ResponseResult.success("");
    }

    // 拒绝广告 11
    @PutMapping("/{id}/reject")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseResult<?> rejectAdvertisement(@PathVariable Long id) {
        advertisementService.rejectAdvertisement(id);
        return ResponseResult.success("");
    }

    /**
     * 获取当前用户的广告列表
     */
    @GetMapping("/my")
    @PreAuthorize("hasAuthority('ad:list')")
    public ResponseResult<Page<Advertisement>> getMyAdvertisements(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            Integer type) {

        // 从 SecurityContext 获取当前用户ID
        Long userId =  getUserId();

        log.info("userId{}",userId);
        log.info("获取我的广告列表，页码：{}，每页大小：{}，标题：{}，状态：{}，开始日期：{}，结束日期：{}，类型：{}", pageNum, pageSize, title, status, startDate, endDate, type);
        return ResponseResult.success(
                advertisementService.getAdvertisementsByUserId(
                        userId, pageNum, pageSize, title, status, startDate, endDate,type
                )
        );
    }

    private Long getUserId() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        return loginUser.getUser().getId();
    }

}